package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository //此注解一般用于描述数据逻辑层的具体实现对象，此对象要交给spring管理
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;
        Statement stat = null;
        ResultSet re = null;
        String Sql = "select * from tb_goods";
        try {
            //1,获取jdbc连接
            conn = dataSource.getConnection();
            //2,创建Statement对象，基于此对象发送SQL
            stat = conn.createStatement();
            //3,发送SQL，执行查询
            re = stat.executeQuery(Sql);
            //4,处理结果集（将所有记录封装到List<Map<String,Object>>）
            List<Map<String ,Object>> list = new ArrayList<>();
            while (re.next()){
                list.add(rowMap(re));
            }
            return list;
        } catch (SQLException a) {
            a.printStackTrace();
            throw new RuntimeException();//非检查异常，这样方法就不需要声明抛出了
        }finally {
            //5,释放资源
            if (re != null)try {re.close();}catch (Exception e){e.printStackTrace();}
            if (stat != null)try {stat.close();}catch (Exception e){e.printStackTrace();}
            //这里的连接是返回到了池中
            if (conn != null)try {conn.close();}catch (Exception e){e.printStackTrace();}
        }

    }

    private Map<String, Object> rowMap(ResultSet re) throws SQLException {
        Map<String, Object> rowMap = new HashMap<>();
        //方法1
        rowMap.put("id",re.getInt("id"));
        rowMap.put("name",re.getString("name"));
        rowMap.put("remark",re.getString("remark"));
        rowMap.put("createdTime",re.getString("createdTime"));
        return rowMap;
    }

    private void close(ResultSet re,Statement stat,Connection conn){

    }
}
